<?php
namespace Addons\Avatar;
use Common\Controller\Addon;
use Think\Db;
/**
 * 头像插件
 * @author 丰收的季节
 */
class AvatarAddon extends Addon{

    public $info = array(
        'name'=>'Avatar',
        'title'=>'头像',
        'description'=>'头像上传裁剪',
        'status'=>1,
        'author'=>'丰收的季节',
        'version'=>'1.0'
    );

    public function install(){ //安装时为 member 增加 avatar 字段 需要判断是否有这字段 , 安装移值测试 发布插件
        $db_config = array();
        $db_config['DB_TYPE'] = C('DB_TYPE');
        $db_config['DB_HOST'] = C('DB_HOST');
        $db_config['DB_NAME'] = C('DB_NAME');
        $db_config['DB_USER'] = C('DB_USER');
        $db_config['DB_PWD'] = C('DB_PWD');
        $db_config['DB_PORT'] = C('DB_PORT');
        $db_config['DB_PREFIX'] = C('DB_PREFIX');
        $db = Db::getInstance($db_config);
        $sql = 'alter table '.$db_config['DB_PREFIX'].'user_member add avatar int not null default 0';
        $db->execute($sql);
        return true;
    }

    public function uninstall(){
        $db_config = array();
        $db_config['DB_TYPE'] = C('DB_TYPE');
        $db_config['DB_HOST'] = C('DB_HOST');
        $db_config['DB_NAME'] = C('DB_NAME');
        $db_config['DB_USER'] = C('DB_USER');
        $db_config['DB_PWD'] = C('DB_PWD');
        $db_config['DB_PORT'] = C('DB_PORT');
        $db_config['DB_PREFIX'] = C('DB_PREFIX');
        $db = Db::getInstance($db_config);
        $sql = 'alter table '.$db_config['DB_PREFIX'].'user_member drop column avatar';
        $db->execute($sql);
        return true;
    }

    //实现的avatar钩子方法
    public function avatar($param){
        //显示视图
        $config = $this->getConfig();
      
        $picInfo= $this->getAvatar();
        $config['scale'] = empty($config['scale']) ? '1/1' : $config['scale'];
        $this->assign('picInfo', $picInfo);
        $this->assign('config', $config);
        $this->display('View/defaultMobile');
    }
    //获取当前登录用户头像
    public function getAvatar(){
        $uid = is_login();
        $config = $this->getConfig();
        $prefix = empty($config['prefix']) ? 'avatar_' : $config['prefix'];
        if($uid) {
            $pic_id = M("UserMember")->where(array('status' => 1, 'uid' => $uid))->getField('avatar');
            $info['path']   = 'http://' . $_SERVER['HTTP_HOST'] .__ROOT__;
            $picPath        = get_cover($pic_id, 'path');
            $avatarObj      = A('Addons://Avatar/Avatar');
            $avatarPath     = $avatarObj->picPrefix($picPath, $prefix);
            $info['path']   = $info['path'] . $avatarPath;
            $info['pic_id'] = $pic_id;
            return $info;
        }
        return null;
    }

}